package com.tang.wx.handler;

import com.tang.common.redis.CaptchaKeyBuilder;
import com.tang.component.redis.RedisUtil;
import com.tang.wx.enums.WxMsgTypeEnum;
import com.tang.wx.utils.WxMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CaptchaMsgHandler implements WxMsgHandler {

    public static final String KEY_WORD = "验证码";
    public static final int CAPTCHA_MAX_VALUE = 99999;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxMsgTypeEnum getMsgType() {
        return WxMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String handleMsg(Map<String, String> msgMap) {
        log.info("接收用户消息事件");
        if (!StringUtils.equals(KEY_WORD, msgMap.get("Content"))) {
            return "";
        }
        ThreadLocalRandom current = ThreadLocalRandom.current();
        int nextInt = current.nextInt(current.nextInt(CAPTCHA_MAX_VALUE));
        String captcha = String.format("%05d", nextInt);
        String content = "您的验证码为：" + captcha + "，五分钟之内有效";
        redisUtil.setNx(CaptchaKeyBuilder.getCaptchaKey(captcha), msgMap.get("FromUserName"), 5L, TimeUnit.MINUTES);
        return WxMsgUtil.buildTextMsg(msgMap, content);
    }
}
